package com.imflea.zero.service.pay.impl;

import com.github.jaemon.dinger.DingerSender;
import com.github.jaemon.dinger.core.entity.DingerRequest;
import com.github.jaemon.dinger.core.entity.enums.DingerType;
import com.github.jaemon.dinger.core.entity.enums.MessageSubType;
import com.imflea.zero.constant.AdoptConstant;
import com.imflea.zero.constant.PayConstant;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.entity.meeting.MeetingOrderInfo;
import com.imflea.zero.model.entity.pay.dto.PayOrderDetailDto;
import com.imflea.zero.model.entity.pay.dto.PayPreRecorderDto;
import com.imflea.zero.model.entity.pay.dto.PaySuccessDto;
import com.imflea.zero.model.entity.pay.vo.PayPreDataVo;
import com.imflea.zero.model.entity.pay.vo.PayPreRefundVo;
import com.imflea.zero.service.meeting.IMeetingOrderInfoService;
import com.imflea.zero.service.pay.IHandleCommonPrePayService;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.utils.OrderUtils;
import com.imflea.zero.utils.SessionUtils;
import com.imflea.zero.utils.TaskTimeOutUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("meetingPrePayService")
@Slf4j
public class HandleMeetingPrePayServiceImpl implements IHandleCommonPrePayService {
    @Autowired
    private IMeetingOrderInfoService meetingOrderInfoService;
    @Autowired
    private DingerSender dingerSender;

    @Override
    public PayPreDataVo getPrePayData(PayOrderDetailDto payPreOrderDto) throws Exception {
        PayPreDataVo vo = new PayPreDataVo();
        List<String> orderIds = payPreOrderDto.getOrderIds();

        StringBuffer goodNamesBuf = new StringBuffer("");
        //统一支付流水号
        String paySn = OrderUtils.generateOrderSn();
        List<PayPreRecorderDto> preRecorders = new ArrayList<>();
        if (CommonUtils.isNull(orderIds)) {
            throw new BizException("订单id为空");
        }
        List<MeetingOrderInfo> orderInfos = meetingOrderInfoService.listByIds(orderIds);
        if (CommonUtils.isNull(orderInfos)) {
            throw new BizException("未找到有效的订单");
        }
        if (orderIds.size() != orderIds.size()) {
            throw new BizException("订单不匹配");
        }
        BigDecimal totalPay = new BigDecimal(0);
        for (MeetingOrderInfo info : orderInfos) {
            totalPay = totalPay.add(info.getPayAmount());
            PayPreRecorderDto dto = new PayPreRecorderDto();
            dto.setOrderId(info.getId());
            dto.setTenantId(info.getTenantId());
            dto.setOrderSn(info.getOrderSn());
            dto.setOrderType(PayConstant.ORDER_TYPE_MEETING_CZ.getCode());
            dto.setTotalAmount(info.getPayAmount());
            dto.setPayTime(LocalDateTime.now());
            dto.setPayUserId(SessionUtils.getUserId());
            dto.setPayUserName(SessionUtils.getWxNickName());
            dto.setPayUserOpenId(SessionUtils.getOpenId());
            goodNamesBuf.append(info.getBizName());
            goodNamesBuf.append(",");
            preRecorders.add(dto);
        }
        vo.setPayType(payPreOrderDto.getPayType());
        String goodsName = goodNamesBuf.toString();
        vo.setGoodsName(goodsName.substring(0, goodsName.length() - 1));
        vo.setPaySn(paySn);
        vo.setPayTotal(totalPay);
        vo.setPreRecorders(preRecorders);
        return vo;
    }

    @Override
    public boolean handleCreatePrePayResult(List<String> orderIds, String payType) {

        boolean result = meetingOrderInfoService.updatePayTypeByIds(orderIds, payType);
        for (String id : orderIds) {
            if (payType.equals(PayConstant.PAY_TYPE_WX.getCode())) {
                TaskTimeOutUtil.enqueue(AdoptConstant.ADOPT_TIME_OUT_SQU.getCode(), id, Integer.valueOf(AdoptConstant.ADOPT_TIME_OUT_TIME_SECONDS.getCode()));
            } else {
                TaskTimeOutUtil.enqueue(AdoptConstant.ADOPT_TIME_OUT_SQU.getCode(), id, Integer.valueOf(AdoptConstant.ADOPT_TIME_OUT_TIME_SECONDS_TRANSFER.getCode()));
            }
        }

        //是否更新

        return true;
    }

    @Override
    public boolean handlePaySuccess(List<PaySuccessDto> dtos) {
        try {
            List<MeetingOrderInfo> orderInfos = meetingOrderInfoService.listByIds(dtos.stream().map(item -> item.getOrderId()).collect(Collectors.toList()));
            List<String> orders = orderInfos.stream().map(item -> item.getOrderSn()).collect(Collectors.toList());
            int size = orders.size();
            StringBuffer snos = new StringBuffer("");
            for (int i = 0; i < size; i++) {
                String sno = orders.get(i);
                snos.append(sno);
                if (i + 1 < size) {
                    snos.append(",");
                }
            }
            dingerSender.send(DingerType.WETALK, MessageSubType.TEXT, DingerRequest.request("您有" + size + "条新的充值订单，订单号为：" + snos.toString()));
        } catch (Exception e) {
            log.error("订单推送异常", e.getMessage());
        }
        boolean order2CompletedResult = meetingOrderInfoService.changeOrder2Complete(dtos, dtos.get(0).getPaySn(), dtos.get(0).getPayType());
        return order2CompletedResult;
    }

    @Override
    public PayPreRefundVo getPreRefundData(String refundOrderId, String orderType, String extend) {
        return null;
    }

    @Override
    public boolean handleRefundSuccess(String refundOrderId, String orderType, String extend) {
        return false;
//        boolean result = this..update2RefundSuccess(refundOrderId);
//        return result;
    }
}
